package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.dto.UserDTO;
import com.leyou.user.client.UserClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApplicationInfoMapper infoMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String USER_ROLE = "role_user";

    public void login(String username, String password, HttpServletResponse response) {

        try {
            UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);
            // 生成userInfo, 没写权限功能，暂时都用guest
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), USER_ROLE);
            // 生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), prop.getUser().getExpire());

            CookieUtils.newBuilder().domain(prop.getUser().getCookieDomain()).maxAge(prop.getUser().getExpire()*60)
                    .name(prop.getUser().getCookieName()).response(response).value(token).httpOnly(true).build();
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.USER_NAME_OR_PASSWORD_ERROR);
        }

    }

    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取cookie
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            // 获取token信息
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            // 获取token的id，校验黑名单
            String id = payLoad.getId();
            Boolean boo = redisTemplate.hasKey(id);
            if (boo != null && boo) {
                // 抛出异常，证明token无效，直接返回401
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            // 获取过期时间
            Date expiration = payLoad.getExpiration();
            // 获取刷新时间
            DateTime refreshTime = new DateTime(expiration.getTime()).plusMinutes(prop.getUser().getMinRefreshInterval());
            // 判断是否已经过了刷新时间
            if (refreshTime.isBefore(System.currentTimeMillis())) {
                // 如果过了刷新时间，则生成新token
                token = JwtUtils.generateTokenExpireInMinutes(payLoad.getInfo(), prop.getPrivateKey(), prop.getUser().getExpire());
                // 写入cookie
                CookieUtils.newBuilder()
                        // response,用于写cookie
                        .response(response)
                        // 保证安全防止XSS攻击，不允许JS操作cookie
                        .httpOnly(true)
                        // 设置domain
                        .domain(prop.getUser().getCookieDomain())
                        // 设置cookie名称和值
                        .name(prop.getUser().getCookieName()).value(token)
                        // 写cookie
                        .build();
            }
            return payLoad.getInfo();
        } catch (Exception e) {
            // 抛出异常，证明token无效，直接返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {

        try {
            // 获取token
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            // 解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            // 获取id和有效期剩余时长
            String id = payload.getId();
            long time = payload.getExpiration().getTime() - System.currentTimeMillis();
            // 写入redis, 剩余时间超过5秒以上才写
            if (time > 5000) {
                redisTemplate.opsForValue().set(id, "", time, TimeUnit.MILLISECONDS);
            }

            //生成新的cookie
            Cookie cookie=new Cookie(prop.getUser().getCookieName(),"");
            cookie.setDomain(prop.getUser().getCookieDomain());
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String authenticate(Long id, String secret) {

        try {
            ApplicationInfo app = infoMapper.selectByPrimaryKey(id);

            if (app==null){
                throw new LyException(ExceptionEnum.INVALID_ID_SECRET);
            }
            if (!passwordEncoder.matches(secret,app.getSecret())){
                throw new LyException(ExceptionEnum.INVALID_ID_SECRET);
            }
            AppInfo appInfo=new AppInfo();
            appInfo.setId(id);
            appInfo.setServiceName(app.getServiceName());
            appInfo.setTargetList(infoMapper.queryTargetIdList(id));
            String token = JwtUtils.generateTokenExpireInMinutes(appInfo, prop.getPrivateKey(), prop.getApp().getExpire());
            return token;
        } catch (LyException e) {
            throw new LyException(ExceptionEnum.INNER_SERVICE_ERROR);
        }

    }
}
